package com.cskaoyan.controller;

import com.cskaoyan.bean.MarketStorage;
import com.cskaoyan.bean.common.BaseRespVo;
import com.cskaoyan.bean.vo.WxStorageUploadVo;
import com.cskaoyan.service.WxStorageService;
import com.cskaoyan.utils.StaticFilePath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

/**
 * 图片上传
 * @Author: JianhuaZeng
 * @Date: 2023/1/2 14:33
 */
@RestController
@RequestMapping("wx/storage")
public class WxStorageController {

    @Autowired
    WxStorageService wxStorageService;

    @PostMapping("upload")
    public BaseRespVo upload(MultipartFile file){
        Date date = new Date();
        String name = file.getOriginalFilename();
        String key = UUID.randomUUID() + name;
        String type = "image/jpeg";
        Integer size = Math.toIntExact(file.getSize());
        String url = StaticFilePath.getPicUrl(key);
        Date addTime = date;
        Date updateTime = date;
        Boolean deleted = false;
        // 文件保存到本地
        try {
            file.transferTo(new File(StaticFilePath.getStaticPath(),key));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 插入数据库记录
        Integer id = wxStorageService.insert(new MarketStorage(null,key,name,type,size,url,addTime,updateTime,deleted));
        // 构造返回对象
        WxStorageUploadVo uploadVo = new WxStorageUploadVo(id,key,name,type,size,url,addTime,updateTime);
        return BaseRespVo.ok(uploadVo,"成功");
    }
}
